import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  Button,
  FlatList,
  Image,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
} from 'react-native';
import useHideTabBar from '../utils/useHideTabBar';
import theme from '../utils/theme';
import API, {getUserId} from '../Network/Api';
import Toast from 'react-native-toast-message';
import {showToast} from '../utils/toastUtils';
import {normalize, screenHeight} from '../utils/commonUtils';
import {CustomText} from '../customview/CustomText';

const ProductPage = ({navigation, route}) => {
  const {sessionInfo, isMember} = route.params;
  const [currentPage, setCurrentPage] = useState(1);
  const [products, setProducts] = useState([]);
  const [purchasedItems, setPurchasedItems] = useState([]);
  const [timer, setTimer] = useState(0);
  const [status, setStatus] = useState('');
  const [totalPages, setTotalPages] = useState(0); // 新增总页数状态
  const [isPurchaseLocked, setIsPurchaseLocked] = useState(false);

  useHideTabBar(navigation);

  useEffect(() => {
    getPurchasedOrder();
    fetchProducts();
    const interval = setInterval(() => {
      const now = new Date();
      const startTime = new Date();
      const endTime = new Date();

      const [startHours, startMinutes] = sessionInfo.cckssj
        .split(':')
        .map(Number);
      const [endHours, endMinutes] = sessionInfo.ccjssj.split(':').map(Number);

      startTime.setHours(startHours, startMinutes, 0, 0);
      endTime.setHours(endHours, endMinutes, 0, 0);

      if (isMember) {
        startTime.setMinutes(startTime.getMinutes() - 1);
      }

      if (now < startTime) {
        const difference = startTime - now;
        const hoursRemaining = Math.floor(difference / 3600000);
        const minutesRemaining = Math.floor((difference % 3600000) / 60000);
        const secondsRemaining = Math.floor((difference % 60000) / 1000);
        setTimer(difference / 1000);
        setStatus(
          `入场倒计时 ${hoursRemaining
            .toString()
            .padStart(2, '0')}:${minutesRemaining
            .toString()
            .padStart(2, '0')}:${secondsRemaining.toString().padStart(2, '0')}`,
        );
      } else if (now >= startTime && now < endTime) {
        const difference = endTime - now;
        const hoursRemaining = Math.floor(difference / 3600000);
        const minutesRemaining = Math.floor((difference % 3600000) / 60000);
        const secondsRemaining = Math.floor((difference % 60000) / 1000);
        setTimer(difference / 1000);
        setStatus(
          `结束倒计时 ${hoursRemaining
            .toString()
            .padStart(2, '0')}:${minutesRemaining
            .toString()
            .padStart(2, '0')}:${secondsRemaining.toString().padStart(2, '0')}`,
        );
      } else {
        setTimer(0);
        setStatus('已结束');
        clearInterval(interval);
      }
    }, 1000);

    return () => clearInterval(interval);
  }, [sessionInfo, isMember]);

  const getPurchasedOrder = () => {
    try {
      API.getPurchasedOrderInfoList()
        .then(async response => {
          if (response.resultCode === '1') {
            const orderData = response.data.orderInfo.rows;
            const data = orderData.map((item, index) => {
              let priceStr =
                item.spjg || Math.floor(Math.random() * 3000).toString();
              let priceNum = parseFloat(priceStr);
              let priceFixed = priceNum.toFixed(2);
              let finalPrice = parseFloat(priceFixed);
              return {
                id: item.id || index + 1,
                name: item.spbt || `商品 ${index + 1}`,
                price: priceFixed,
                quantity: (finalPrice / theme.app.unitPrice).toFixed(0),
                image: theme.app.productImg,
              };
            });
            setPurchasedItems(data);
          }
        })
        .catch(error => {
          showToast({text2: '获取总购买订单数据失败！'});
        });
    } catch (error) {
      console.error('获取场次失败:', error);
    } finally {
    }
  };

  const fetchProducts = async () => {
    API.panicGoodsReq('', sessionInfo.ccbt, '3', '1', '300', '')
      .then(response => {
        if (response.resultCode === '1') {
          const fetchedData = response.data.panicGoods.rows;
          const filteredData = fetchedData.filter(
            item => item.yhid !== getUserId(),
          );
          const data = filteredData.map((item, index) => {
            let priceStr =
              item.spjg || Math.floor(Math.random() * 3000).toString();
            let priceNum = parseFloat(priceStr);
            let priceFixed = priceNum.toFixed(2);
            let finalPrice = parseFloat(priceFixed);
            return {
              id: item.id || index + 1,
              name: item.spbt || `商品 ${index + 1}`,
              price: priceFixed,
              quantity: (finalPrice / theme.app.unitPrice).toFixed(0),
              image: theme.app.productImg,
            };
          });
          const paginatedData = paginateProducts(data, 20);
          setProducts(paginatedData);
          setTotalPages(paginatedData.length); // 设置总页数
          if (currentPage > paginatedData.length) {
            setCurrentPage(paginatedData.length);
          }
        } else if (response.hasProperty('errorMsg')) {
          showToast({
            text2: response.errorMsg,
          });
        } else {
          showToast({
            text2: '网络异常！',
          });
        }
      })
      .catch(error => {
        showToast({
          text2: '服务器异常',
        });
      });
  };

  const paginateProducts = (data, itemsPerPage) => {
    let result = [];
    for (let i = 0; i < data.length; i += itemsPerPage) {
      result.push(data.slice(i, i + itemsPerPage));
    }
    return result;
  };

  const handlePurchase = async product => {
    if (isPurchaseLocked) {
      showToast({text2: '抢购太频繁，请稍后！'});
      return;
    }
    // 开始抢购，设置锁定状态
    setIsPurchaseLocked(true);

    const now = new Date();
    const startTime = new Date();
    const endTime = new Date();
    const privilegeTime = new Date();

    const [startHours, startMinutes] = sessionInfo.cckssj
      .split(':')
      .map(Number);
    const [endHours, endMinutes] = sessionInfo.ccjssj.split(':').map(Number);

    startTime.setHours(startHours, startMinutes, 0, 0);
    privilegeTime.setHours(startHours, startMinutes, 0, 0);
    endTime.setHours(endHours, endMinutes, 0, 0);
    if (isMember) {
      privilegeTime.setMinutes(startTime.getMinutes() - 1);
    }

    if (now < privilegeTime) {
      showToast({text2: '还未开始抢购'});
      setIsPurchaseLocked(false);
      return;
    }
    if (now >= endTime) {
      showToast({text2: '抢购已结束'});
      setIsPurchaseLocked(false);
      return;
    }

    if (privilegeTime < now && now < startTime && purchasedItems.length >= 3) {
      showToast({text2: '特权时间最多抢购3单'});
      setIsPurchaseLocked(false);
      return;
    }

    if (purchasedItems.length >= 6) {
      showToast({text2: '当日最多抢购6单'});
      setIsPurchaseLocked(false);
      return;
    }

    API.updateGoodsStatus('4', product.id, getUserId())
      .then(async response => {
        if (response.resultCode === '1') {
          showToast({text2: '抢购成功！', visibilityTime: 1000});
          const updatedProducts = products.map(page =>
            page.filter(item => {
              return item.id !== product.id;
            }),
          );
          setProducts(updatedProducts);
          await getPurchasedOrder();
          setIsPurchaseLocked(false);
        } else if (response.data.errMsg) {
          showToast({text2: response.data.errMsg});
        } else {
          showToast({text2: '商品已抢购！'});
        }
        // 抢购操作结束，解除锁定状态
        setIsPurchaseLocked(false);
      })
      .catch(error => {
        console.error('抢购失败:', error);
        showToast({text2: '商品已抢购！（请联系管理员）'});
        // 抢购失败，解除锁定状态
        setIsPurchaseLocked(false);
      });
  };

  const renderProduct = ({item}) => (
    <View style={styles.productContainer}>
      <Image source={item.image} style={styles.productImage} />
      <CustomText style={styles.nameStyle}>{item.name}</CustomText>
      <CustomText style={styles.priceStyle}>¥{item.price}</CustomText>
      <View style={styles.quantityContainer}>
        <CustomText style={styles.priceStyle}>≈{item.quantity}瓶</CustomText>
      </View>
      <TouchableOpacity
        style={styles.buttonStyle}
        onPress={() => handlePurchase(item)}>
        <CustomText style={styles.buttonTitleStyle}>立即批发</CustomText>
      </TouchableOpacity>
    </View>
  );

  const totalAmount = purchasedItems.reduce(
    (sum, item) => sum + parseFloat(item.price),
    0,
  );

  const EmptyListComponent = () => (
    <View style={styles.emptyListContainer}>
      <CustomText style={styles.emptyListText}>暂无批发商品</CustomText>
    </View>
  );

  const renderStatusText = () => {
    if (status.includes('入场')) {
      let newStatus = status.replace('入场倒计时', '');
      return (
        <View style={styles.statusContainer}>
          <CustomText style={styles.statusTextStyle}>入场倒计时</CustomText>
          <CustomText style={styles.timeText}>{newStatus}</CustomText>
        </View>
      );
    } else if (status.includes('结束')) {
      let newStatus = status.replace('结束倒计时', '');
      return (
        <View style={styles.statusContainer}>
          <CustomText style={styles.statusTextStyle}>结束倒计时</CustomText>
          <CustomText style={styles.timeText}>{newStatus}</CustomText>
        </View>
      );
    } else if (status.length > 0) {
      return <CustomText style={styles.timeText}>{status}</CustomText>;
    } else {
      return null;
    }
  };

  const onRefreshData = () => {
    fetchProducts();
    getPurchasedOrder();
  };

  return (
    <View style={styles.container}>
      <View style={styles.timerContainer}>{renderStatusText()}</View>
      <View style={styles.headerContainer}>
        <CustomText style={styles.moneyText}>
          批发金额: {totalAmount.toFixed(2)}元 ({purchasedItems.length}单)
        </CustomText>
        <View style={{flexDirection: 'row'}}>
          <TouchableOpacity
            style={{flexDirection: 'row', alignItems: 'center'}}
            onPress={onRefreshData}>
            <Image
              style={styles.shuaxinStyle}
              source={require('../../res/image/shuaxin.png')}
            />
            <CustomText style={styles.shuaxinText}>刷新</CustomText>
          </TouchableOpacity>
        </View>
      </View>

      {/* 动态分页 */}
      <View style={styles.paginationContainer}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          {Array.from({length: totalPages}, (_, i) => i + 1).map(page => (
            <TouchableOpacity
              key={page}
              style={[
                styles.pageButton,
                currentPage === page && styles.activePageButton,
              ]}
              onPress={() => setCurrentPage(page)}>
              <CustomText
                style={[
                  styles.pageButtonText,
                  currentPage === page && styles.activePageButtonText,
                ]}>
                第{page}页
              </CustomText>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      {/* 商品列表 */}
      <FlatList
        data={products[currentPage - 1] || []}
        numColumns={2}
        renderItem={renderProduct}
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={styles.flatListContent}
        ListEmptyComponent={EmptyListComponent}
      />
      <Toast />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f6f6f6',
  },
  timerContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    height: 50,
  },
  paginationContainer: {
    flexDirection: 'row',
    paddingVertical: 5,
    backgroundColor: '#ffffff',
  },
  pageButton: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    marginHorizontal: 5,
    borderRadius: 5,
    backgroundColor: '#f0f0f0',
  },
  activePageButton: {
    backgroundColor: theme.colors.primary,
  },
  pageButtonText: {
    color: '#333',
  },
  activePageButtonText: {
    color: '#fff',
  },
  flatListContent: {
    paddingBottom: 90,
  },
  productContainer: {
    width: '45%',
    marginTop: 10,
    marginHorizontal: 10,
    backgroundColor: '#fff',
    borderRadius: 10,
  },
  productImage: {
    height: 130,
    width: 130,
    alignSelf: 'center',
    marginTop: 10,
  },
  nameStyle: {
    fontWeight: '500',
    fontSize: normalize(14),
    color: '#191919',
    marginTop: 10,
    marginHorizontal: 20,
  },
  priceStyle: {
    marginTop: 5,
    marginHorizontal: 20,
    fontWeight: '600',
    fontSize: normalize(16),
    color: theme.colors.primary,
  },
  quantityContainer: {
    flex: 1,
    alignItems: 'flex-end',
  },
  buttonStyle: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignSelf: 'center',
    width: '80%',
    height: 30,
    backgroundColor: theme.colors.primary,
    borderRadius: 5,
    marginVertical: 10,
  },
  buttonTitleStyle: {
    alignSelf: 'center',
    color: 'white',
  },
  headerContainer: {
    height: 20,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    backgroundColor: '#fff',
  },
  shuaxinStyle: {
    width: 20,
    height: 20,
  },
  shuaxinText: {
    marginLeft: 3,
  },
  moneyText: {
    color: theme.colors.accent,
  },
  emptyListContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: screenHeight / 3,
  },
  emptyListText: {
    flex: 1,
    fontSize: normalize(16),
    color: '#999',
  },
  statusContainer: {
    flexDirection: 'row',
    paddingVertical: 10,
    alignItems: 'center',
  },
  timeText: {
    color: theme.colors.accent,
    fontWeight: '500',
    borderColor: theme.colors.accent,
    borderWidth: 1,
    paddingHorizontal: 5,
    paddingVertical: 3.5,
    width: 80,
  },
  statusTextStyle: {
    color: '#fff',
    fontSize: normalize(12),
    marginLeft: 10,
    backgroundColor: theme.colors.accent,
    paddingHorizontal: 5,
    paddingVertical: 6,
  },
});

export default ProductPage;
